﻿/* 
 * Inspired by Freshclickmedia.Web
 * http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MVCCentral.Framework.Mvc
{
    /// <summary>
    /// Part of the GizmoBeach.Framework.
    /// </summary>
    public static class GravatarHtmlHelper
    {
        public enum RatingType { G, PG, R, X }

        public static string Gravatar(this HtmlHelper helper, string Email)
        {
            return Gravatar(helper, Email, 80, string.Empty, RatingType.G, string.Empty);
        }
        public static string Gravatar(this HtmlHelper helper, string Email, short Size)
        {
            return Gravatar(helper, Email, Size, string.Empty, RatingType.G, string.Empty);
        }
        public static string Gravatar(this HtmlHelper helper, string Email, short Size, string DefaultImage)
        {
            return Gravatar(helper, Email, Size, DefaultImage, RatingType.G, string.Empty);
        }
        public static string Gravatar(this HtmlHelper helper, string Email, short Size, string DefaultImage, RatingType Rating)
        {
            return Gravatar(helper, Email, Size, DefaultImage, Rating, string.Empty);
        }
        public static string Gravatar(this HtmlHelper helper, string Email, short Size, string DefaultImage, RatingType Rating, string Alt)
        {
            string imageUrl = "http://www.gravatar.com/avatar.php?";

            try
            {
                // if it's not in the allowed range, throw an exception:
                if (Size < 1 || Size > 512)
                    throw new ArgumentOutOfRangeException();
            }
            catch
            {
                Size = 80;
            }

            if (!string.IsNullOrEmpty(Email))
            {
                imageUrl += "gravatar_id=" + MD5Hasher.GetEmailHash(Email);
                imageUrl += "&rating=" + Rating.ToString();
                imageUrl += "&size=" + Size.ToString();
            }

            // output default parameter if specified
            if (!string.IsNullOrEmpty(DefaultImage))
            {
                imageUrl += "&default=" + DefaultImage;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<a href=\"http://www.gravatar.com\" target=\"_blank\" title=\"Get your Free Gravatar\">");
            sb.Append("<img src=\"");
            sb.Append(imageUrl);
            sb.Append("\"");
            if (!string.IsNullOrEmpty(Alt)) sb.Append(" alt=\"" + Alt + "\"");
            sb.Append(" />");
            sb.Append("</a>");

            return sb.ToString();
        }
    }
}
